package com.cloud.mybatis.service.impl;


import com.cloud.mybatis.entity.UserEntity;
import com.cloud.mybatis.mapper.UserMapper;
import com.cloud.mybatis.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author hantianyang
 * @ClassName UserServiceImpl
 * @date 2024/5/25
 */
@Service
public class UserServiceImpl implements UsersService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ProductService productService;
    @Autowired
    private PersionService persionService;
    @Autowired
    private PlatformTransactionManager transactionManager;

    @Override
    @Transactional
    public void add(UserEntity userEntity) {

        userMapper.add(userEntity);
        // 当加了事务注解  才会进来，否则进不来
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            // 注册事务同步回调
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    System.out.println("事务提交后处理业务逻辑");
                    // 在事务提交后执行的逻辑
                    // 可以进行一些清理工作或发送通知
                }

                @Override
                public void afterCompletion(int status) {
                    // 在事务完成后执行的逻辑
                    // status表示事务的状态，可以根据不同状态执行不同的操作
                    System.out.println(status);
                    if (status == STATUS_COMMITTED) {
                        System.out.println("Transaction committed successfully.");
                        // 执行事务成功提交后的逻辑
                    } else if (status == STATUS_ROLLED_BACK) {
                        System.out.println("Transaction rolled back.");
                        // 执行事务回滚后的逻辑
                    } else if (status == STATUS_UNKNOWN) {
                        System.out.println("Transaction status is unknown.");
                        // 处理事务状态未知的情况
                    }
                }

                @Override
                public void beforeCommit(boolean readOnly) {
                    // 在事务提交前执行的逻辑
                    // readOnly表示事务是否为只读
                }

                @Override
                public void beforeCompletion() {
                    // 在事务完成前执行的逻辑
                }
            });
        }
    }

    @Override
    public List<UserEntity> getList() {
        return userMapper.getList();
    }

    @Override
    @Transactional
    public void test() {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            UserEntity userEntity = new UserEntity();
            userEntity.setName("test");
            userMapper.add(userEntity);
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    // 事务提交后执行的逻辑
                    System.out.println("事务已提交，执行后续操作...");
                    CompletableFuture.runAsync(new Runnable() {
                        @Override
                        public void run() {

                            // 定义事务属性（如超时时间、隔离级别等）
                            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                            def.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRES_NEW);
                            TransactionStatus status = transactionManager.getTransaction(def);
                            try {
                                productService.save();
                                persionService.save();
//                                int i=1/0;
                                transactionManager.commit(status); // 全部成功则提交
                            } catch (Exception e) {
                                transactionManager.rollback(status); // 任一失败则回滚
                            }
                        }
                    });
                }
            });
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
            throw e;
        }
    }
}
